package com.scs.application.modules.wm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.SerialKeys;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UtilNum;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.service.MatrService;
import com.scs.application.modules.base.util.CommonService;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.dto.ProcessDTO;
import com.scs.application.modules.wm.entity.*;
import com.scs.application.modules.wm.enums.LockBusType;
import com.scs.application.modules.wm.enums.ProcessTypes;
import com.scs.application.modules.wm.enums.UniqueCodeType;
import com.scs.application.modules.wm.mapper.StockProcessMapper;
import com.scs.application.modules.wm.service.*;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class StockProcessServiceImpl extends BaseServiceImpl<StockProcessMapper, StockProcess> implements StockProcessService {

    @Autowired
    private StockProcessItemService stockProcessItemService;

    @Autowired
    private StockZeroService stockZeroService;
    @Autowired
    private StockService stockService;

    @Autowired
    private StockLockService stockLockService;

    @Autowired
    private MatrService matrService;

    @Override
    public boolean saveOrUpdate(StockProcess entity) {
        if (StringUtils.isBlank(entity.getBusKey())) {
            entity.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.PROCESS_KEY));
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean process(ProcessDTO stockProcess) {
        Stock stock = stockService.getExpStockById(stockProcess.getStockId(), true);
        if (stock == null || stock.getSkuQty() == 0) {
            throw new BusinessException("库存为0不可进行加工");
        }
        //直接去掉该判断，正在加工的会加锁，所以不需要做判断
//        List<StockProcess> stockProcesses = this.list(Wrappers.<StockProcess>query().eq("sn",stockProcess.getSn()).eq("process_type", stockProcess.getProcessType()));
//        if(stockProcesses != null && stockProcesses.size()>0){
//            throw new BusinessException("该库存已经%s，请勿重复操作",stockProcesses.get(0).getSubmitStatus() ? "提交" : "加工");
//        }
//        if(stockProcess.getSubmitStatus() != null && stockProcess.getSubmitStatus()) {
//            throw new BusinessException("已提交的加工单不允许再次加工");
//        }

        Boolean bResult = this.saveOrUpdate(stockProcess);

        if (bResult) {//保存加工明细
            if (ProcessTypes.MERGE.getType().equals(stockProcess.getProcessType())) {
                return processMerge(stockProcess);
            } else {
                return processSplit(stockProcess);
            }
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StockProcess submit(StockProcess stockProcess) {
//        Stock stock = stockService.getByIdWithZero(stockProcess.getStockId());
//        if(stock == null || stock.getSkuQty() == 0){
//            throw new BusinessException("库存为0不可进行提交");
//        }
        stockProcess = baseMapper.selectById(stockProcess.getId());
        if (stockProcess == null) throw new BusinessException("加工单不存在或者已被删除");

        if (stockProcess.getSubmitStatus()) {
            throw new BusinessException("该加工单已提交");
        }

        List<StockProcessItem> stockProcessItems = stockProcessItemService.list(new QueryWrapper<StockProcessItem>().eq("process_id", stockProcess.getId()));
        if (stockProcessItems.size() == 0) {
            throw new BusinessException("没有加工明细，不允许提交");
        }

        if (ProcessTypes.MERGE.getType().equals(stockProcess.getProcessType())) {
            submitMerge(stockProcess, stockProcessItems);
        } else {
            submitSplit(stockProcess, stockProcessItems);
        }
        return baseMapper.selectById(stockProcess.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unSubmit(StockProcess stockProcess) {
        if (!stockProcess.getSubmitStatus()) {
            throw new BusinessException("当前状态不允许撤销");
        }
        if (ProcessTypes.MERGE.getType().equals(stockProcess.getProcessType())) {
            return unSubmitMerge(stockProcess);
        } else {
            return unSubmitSplit(stockProcess);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unProcess(StockProcess stockProcess) {
        if (stockProcess.getSubmitStatus()) {
            throw new BusinessException("当前状态不允许撤销");
        }

        if (ProcessTypes.SPLIT.getType().equals(stockProcess.getProcessType())) {
            List<StockLock> stockLocks = stockLockService.list(new QueryWrapper<StockLock>().eq("stock_id", stockProcess.getStockId()).eq("bus_key_value", stockProcess.getBusKey()));
            if (!stockLocks.isEmpty()) {
                stockLockService.unlockBatch(stockLocks.stream().map(StockLock::getUc).collect(Collectors.toList()));
            }
        }
        return this.removeCascadeById(stockProcess.getId());
    }

    @Override
    public boolean removeCascadeById(Serializable id) {
        StockProcess stockProcess = this.getById(id);
        if (stockProcess == null) {
            return true;
        }
        List<StockProcessItem> processItems = stockProcessItemService.list(new QueryWrapper<StockProcessItem>().eq("process_id", id));
        if (processItems != null && processItems.size() > 0) {
            stockProcessItemService.removeCascadeByIds(processItems.stream().map(StockProcessItem::getId).collect(Collectors.toList()));

            List<StockLock> stockLocks = stockLockService.list(new QueryWrapper<StockLock>().in("stock_id", processItems.stream().map(StockProcessItem::getStockId).collect(Collectors.toList()))
                    .eq("bus_key_value", stockProcess.getBusKey()));
            if (!stockLocks.isEmpty()) {
                stockLockService.unlockBatch(stockLocks.stream().map(StockLock::getUc).collect(Collectors.toList()));
            }
        }
        return super.removeById(id);
    }

    //根据SN获取加工信息
    @Override
    public StockProcess barCodeScan(String sn, Integer processType) {
        Stock stock = stockService.getExpStockByUC(sn);
        if (stock != null) { //不为空，判断是否已经有加工记录
            StockLock stockLock = stockLockService.getOne(new QueryWrapper<StockLock>().eq("stock_id", stock.getId()));
            if (stock.getFlagOmoc()) {
                throw new BusinessException("一物一码耗材不允许进行拆分或者合并操作");
            }
            if (stock.getPackageQty() < 1) {
                throw new BusinessException("该唯一码没有可用库存");
            }
            if (stockLock != null && !stockLock.getBusType().equals(LockBusType.PROCESS.toString())) {
                throw new BusinessException("该耗材已经锁库,无法进行加工 原因" + stockLock.getLockComment());
            }
            if (ProcessTypes.SPLIT.getType().equals(processType)) {
                StockProcess stockProcess = super.getOne(new QueryWrapper<StockProcess>().eq("sn", sn).eq("process_type", processType).orderByDesc("gmt_modified").last("limit 1"));
                if (stockProcess == null) {
                    stockProcess = new StockProcess();
                    BeanUtils.copyProperties(stock, stockProcess);
                    stockProcess.setStockId(stock.getId())
                            .setSubmitStatus(false)
                            .setId(null);
                }
                return stockProcess;
            } else {
                StockProcess stockProcess = super.getOne(new QueryWrapper<StockProcess>()
                        .eq("matr_id", stock.getMatrId())
                        .eq("warehouse_id", stock.getWarehouseId())
                        .eq("package_unit", stock.getPackageUnit())
                        .eq(stock.getLot() != null, "lot", stock.getLot())
                        .eq(stock.getExpDate() != null, "exp_date", stock.getExpDate())
                        .eq("process_type", processType)
                        .orderByDesc("gmt_modified")
                        .last("limit 1"));
                if (stockProcess != null) { //再判断加工明细中是否有该SN
                    StockProcessItem stockProcessItem = stockProcessItemService.getOne(new QueryWrapper<StockProcessItem>()
                            .eq("process_id", stockProcess.getId())
                            .eq("stock_id", stock.getId())
                            .orderByDesc("gmt_modified")
                            .last("limit 1"));
                    if (stockProcessItem != null) {
                        return stockProcess;
                    }
                }
                stockProcess = new StockProcess();
                BeanUtils.copyProperties(stock, stockProcess);
                stockProcess.setStockId(stock.getId())
                        .setSubmitStatus(false)
                        .setId(null);
                return stockProcess;
            }
        } else { //获取以前的加工记录
            StockProcess stockProcess = super.getOne(new QueryWrapper<StockProcess>().eq("sn", sn));
            if (stockProcess == null) {
                StockProcessItem stockProcessItem = stockProcessItemService.getOne(new QueryWrapper<StockProcessItem>()
                        .eq("sn", sn)
                        .orderByDesc("gmt_modified").last("limit 1"));
                if (stockProcessItem != null) {
                    stockProcess = super.getById(stockProcessItem.getProcessId());
                }
            }
            return stockProcess;
        }
    }

    //加工之合并
    private Boolean processMerge(ProcessDTO stockProcess) {
        long beginTime = System.currentTimeMillis();

        if (stockProcess.getStocks() == null || stockProcess.getStocks().size() == 0) {
            throw new BusinessException("没有需要加工的耗材");
        }

        List<StockProcessItem> needRemoveItems = stockProcessItemService.list(new QueryWrapper<StockProcessItem>()
                .eq("process_id", stockProcess.getId())
                .notIn("stock_id", stockProcess.getStocks().stream().map(s -> s.getId()).collect(Collectors.toList())));
        if (needRemoveItems.size() > 0) {
            stockProcessItemService.removeCascadeByIds(needRemoveItems.stream().map(stockProcessItem -> stockProcessItem.getId()).collect(Collectors.toList()));
        }
        List<StockProcessItem> stockProcessItems = Lists.newArrayListWithCapacity(stockProcess.getStocks().size());
        stockProcess.getStocks().forEach(stock -> {
            StockLock stockLock = stockLockService.getOne(new QueryWrapper<StockLock>().eq("stock_id", stock.getId()));
            if (stockLock != null) {
                throw new BusinessException("该耗材已经锁库,无法进行加工 原因" + stockLock.getLockComment() + "[" + stockLock.getUc() + "]");
            }
            if (stockProcessItemService.getOne(new QueryWrapper<StockProcessItem>()
                    .eq("process_id", stockProcess.getId())
                    .eq("stock_id", stock.getId()).orderByDesc("gmt_modified").last("limit 1")) == null) {
                StockProcessItem stockProcessItem = new StockProcessItem();
                BeanUtils.copyProperties(stock, stockProcessItem);
                stockProcessItem.setProcessId(stockProcess.getId())
                        .setStockId(stock.getId())
                        .setId(null);
                stockProcessItems.add(stockProcessItem);
            }
        });
        //加工锁
        stockLockService.lockBatch(LockBusType.PROCESS, stockProcess.getBusKey(), stockProcess.getWarehouseId(), "加工锁", stockProcessItems.stream().map(StockProcessItem::getSn).collect(Collectors.toList()), stockProcess.getBusKey());
        long endTime = System.currentTimeMillis();

        String ms = DateUtils.formatTime(endTime - beginTime);

        logger.info("耗时为：----------------------" + stockProcessItems.size() + "--------------={}", ms);
        return stockProcessItemService.saveBatch(stockProcessItems);
    }

    //加工之拆分
    private Boolean processSplit(ProcessDTO stockProcess) {
        long beginTime = System.currentTimeMillis();

        List<StockProcessItem> stockProcessItems = stockProcessItemService.list(new QueryWrapper<StockProcessItem>().eq("process_id", stockProcess.getId()));
        if (stockProcessItems != null && stockProcessItems.size() > 0) { //已有的数据判断是否符合加工条件
            if (stockProcessItems.size() == stockProcess.getProcessQty().intValue() && stockProcessItems.get(0).getPackageUnit().equals(stockProcess.getPackageProcess())) {
                return true; //无需加工
            } else { //删除原先的加工记录，重新生成新的
                if (stockProcessItems != null && stockProcessItems.size() > 0)
                    stockProcessItemService.removeCascadeByIds(stockProcessItems.stream().map(stockProcessItem -> stockProcessItem.getId()).collect(Collectors.toList()));
            }
        }
        stockProcessItems = Lists.newArrayListWithCapacity(stockProcess.getProcessQty().intValue());
        for (int i = 0; i < stockProcess.getProcessQty(); i++) {
            StockProcessItem stockProcessItem = new StockProcessItem();
            BeanUtils.copyProperties(stockProcess, stockProcessItem);
            stockProcessItem.setPackageUnit(stockProcess.getPackageProcess())
                    .setProcessId(stockProcess.getId())
                    .setSn(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.WM_STOCK_PROCESS_SN))
                    .setRfid(null)
                    .setSkuQty(stockProcess.getSkuQty() / stockProcess.getProcessQty())
                    .setAmount(stockProcessItem.getSkuPrice() * stockProcessItem.getSkuQty())
                    .setStockId(null)
                    .setId(null);
            stockProcessItems.add(stockProcessItem);
        }
        long endTime = System.currentTimeMillis();
        String ms = DateUtils.formatTime(endTime - beginTime);
        stockLockService.lock(LockBusType.PROCESS, stockProcess.getBusKey(), stockProcess.getWarehouseId(), stockProcess.getSn(), UniqueCodeType.SN, "加工锁");
        logger.info("耗时为：----------------------" + stockProcessItems.size() + "--------------={}", ms);
        return stockProcessItemService.saveBatch(stockProcessItems);
    }

    //提交之拆分
    private Boolean submitSplit(StockProcess stockProcess, List<StockProcessItem> stockProcessItems) {
        List<Stock> stocks = Lists.newArrayListWithCapacity(stockProcessItems.size());
        StockLock stockLock = stockLockService.getOne(new QueryWrapper<StockLock>().eq("stock_id", stockProcess.getStockId()));
        if (stockLock != null) {
            if (!stockProcess.getBusKey().equalsIgnoreCase(stockLock.getBusKeyValue())) {
                throw new BusinessException("该耗材已经锁库,无法进行加工 原因" + stockLock.getLockComment());
            } else {
                stockLockService.unlock(stockLock.getStockId());
            }
        }

        Stock stockSN = stockService.getExpStockById(stockProcess.getStockId(), true); //验证效期
        if (stockSN == null || stockSN.getSkuQty() == 0d) {
            throw new BusinessException("该耗材已经被加工: " + stockProcess.getSn());
        }

        stockProcessItems.stream().forEach(stockProcessItem -> {
            Stock stock = new Stock();
            BeanUtils.copyProperties(stockProcessItem, stock);
            stock.setPackageQty(1d)
                    .setId(null);
            //设置货位
            if (StringUtils.isNotBlank(stockProcess.getLocationId())) {
                stock.setLocationId(stockProcess.getLocationId()).setLocationName(stockProcess.getLocationName());
            }
            CommonService.checkStock(stock, null);
            stocks.add(stock);
        });
        stockService.saveBatch(stocks);

        //更新关联的stockId
        stockProcessItems.stream().forEach(stockProcessItem -> {
            Stock stock = stockService.getExpStockByUC(stockProcessItem.getSn());
            if (stock != null) {
                stockProcessItem.setStockId(stock.getId());
            }
        });
        stockProcessItemService.updateBatchById(stockProcessItems);
        stockProcess.setSubmitStatus(true);

        //删除掉原先的SN
        Stock baseStock = new Stock();
        baseStock.setId(stockProcess.getStockId());
        baseStock.setPackageQty(0d);
        baseStock.setSkuQty(0d);
        baseStock.setAmount(0d);
        stockService.updateById(baseStock);
//        stockService.removeById(baseStock);

        return super.updateCascadeById(stockProcess);
    }

    //提交之合并
    private Boolean submitMerge(StockProcess stockProcess, List<StockProcessItem> stockProcessItems) {
        List<StockLock> stockLocks = stockLockService.list(Wrappers.<StockLock>query().in("stock_id", stockProcessItems.stream().map(StockProcessItem::getStockId).collect(Collectors.toList())));
        if (stockLocks != null && !stockLocks.isEmpty()) {
            List<StockLock> otherStockLocks = stockLocks.stream().filter(lock -> !stockProcess.getBusKey().equalsIgnoreCase(lock.getBusKeyValue())).collect(Collectors.toList());
            if (!otherStockLocks.isEmpty()) {
                throw new BusinessException("该耗材已经锁库,无法进行加工 原因" + stockLocks.get(0).getLockComment() + "[" + stockLocks.get(0).getUc() + "]");
            } else {
                stockLockService.unlockBatch(stockLocks.stream().map(StockLock::getUc).collect(Collectors.toList()));
            }
        }
        List<Stock> stocks = stockService.list(Wrappers.<Stock>query().in("id", stockProcessItems.stream().map(StockProcessItem::getStockId).collect(Collectors.toList())).eq("sku_qty", 0));
        if (stocks != null && !stocks.isEmpty()) {
            throw new BusinessException("该耗材已经被加工: " + stocks.get(0).getSn());
        }
        Double skuQty = stockProcessItems.get(0).getSkuQty();
        Stock stock = new Stock();
        BeanUtils.copyProperties(stockProcess, stock);
        stock.setPackageQty(1d)
                .setPackageUnit(stockProcess.getPackageProcess())
                .setSkuQty(stockProcessItems.size() * skuQty)
                .setAmount(UtilNum.mul(stock.getSkuQty(), stock.getSkuPrice()))
                .setSn(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.WM_STOCK_PROCESS_SN))
                .setId(null);
        CommonService.checkStock(stock, null);
        stockService.save(stock);


//        //删除关联的stockId
//        stockService.remove(new QueryWrapper<Stock>().in("id", stockProcessItems.stream().map(stockProcessItem -> stockProcessItem.getStockId()).collect(Collectors.toList())));

        //更新数量为0
        stockService.update(Wrappers.<Stock>update().in("id", stockProcessItems.stream().map(stockProcessItem -> stockProcessItem.getStockId()).collect(Collectors.toList()))
                .set("package_qty", 0)
                .set("sku_qty", 0)
                .set("amount", 0)
        );

        stockProcess.setSn(stock.getSn())
                .setSubmitStatus(true)
                .setSkuQty(stock.getSkuQty())
                .setStockId(stock.getId());

        return super.updateCascadeById(stockProcess);
    }

    //撤销之拆分
    private Boolean unSubmitSplit(StockProcess stockProcess) {
        List<StockProcessItem> stockProcessItems = stockProcessItemService.list(new QueryWrapper<StockProcessItem>().eq("process_id", stockProcess.getId()));
        List<Stock> stocks = stockService.getExpStockById(stockProcessItems.stream().map(StockProcessItem::getStockId).collect(Collectors.toList()));
        List<StockLock> stockLocks = stockLockService.list(new QueryWrapper<StockLock>().in("stock_id", stockProcessItems.stream().map(StockProcessItem::getStockId).collect(Collectors.toList())));
        if (stockProcessItems.size() != stocks.size()) {
            throw new BusinessException("库存已经被使用或者锁定，不允许撤销");
        }

        stocks.stream().filter(stock -> !stock.getWarehouseId().equals(stockProcess.getWarehouseId())).findAny().ifPresent(stock -> {
            throw new BusinessException("库存已经被使用或者锁定，不允许撤销");
        });

        if (stocks.stream().filter(stock -> stock.getSkuQty() == 0).findAny().isPresent() || stockLocks.size() > 0) {
            throw new BusinessException("库存已经被使用或者锁定，不允许撤销");
        }

        Stock stock = stockService.getOne(new QueryWrapper<Stock>().eq("id", stockProcess.getStockId()));
        Matr matr = matrService.getById(stockProcess.getMatrId()); //重新获取一下价格，万一有变价
        if (stock == null) {
            StockZero zero = stockZeroService.getById(stockProcess.getStockId());
            if (zero == null) {
                throw new BusinessException("未查询到库存，无法撤销");
            }
            stock = new Stock();
            BeanUtils.copyProperties(zero, stock);
            stockService.saveOrUpdate(stock);
            stockZeroService.removeCascadeById(zero.id);
        }
        if (stocks != null && stocks.size() > 0) {
            List<String> ids = stocks.stream().map(o -> o.getId()).collect(Collectors.toList());
            stockService.removeByIds(ids);
        }

        stockProcess.setSubmitStatus(false);

        stock.setPackageQty(1d)
                .setSkuUnit(matr.getSkuUnit())
                .setSkuQty(stockProcess.getSkuQty())
                .setSkuPrice(matr.getSkuPrice())
                .setAmount(matr.getSkuPrice() * stock.getSkuQty());
        stockService.updateById(stock);
        stockLockService.lock(LockBusType.PROCESS, stockProcess.getBusKey(), stockProcess.getWarehouseId(), stockProcess.getSn(), UniqueCodeType.SN, "加工锁");
        return super.updateCascadeById(stockProcess);
    }


    //撤销之合并
    private Boolean unSubmitMerge(StockProcess stockProcess) {
        Stock stock = stockService.getOne(new QueryWrapper<Stock>().eq("id", stockProcess.getStockId()));
        StockLock stockLock = stockLockService.getOne(new QueryWrapper<StockLock>().eq("stock_id", stockProcess.getStockId()));
        if (stock == null || stock.getSkuQty() <= 0 || stockLock != null) {
            throw new BusinessException("库存已经被使用或者锁定，不允许撤销");
        }

        List<StockProcessItem> stockProcessItems = stockProcessItemService.list(new QueryWrapper<StockProcessItem>().eq("process_id", stockProcess.getId()));
//        List<Stock> stocks = Lists.newArrayListWithCapacity(stockProcessItems.size());
//        stockProcessItems.forEach(stockProcessItem -> {
//            Stock stock1 = new Stock();
//            BeanUtils.copyProperties(stockProcessItem, stock1);
//            stock1.setPackageQty(1d).setId(null);
//            stocks.add(stock1);
//        });
//
//        stockService.saveBatch(stocks);

        Matr matr = matrService.getById(stockProcess.getMatrId()); //重新获取一下价格，万一有变价
        for (StockProcessItem stockProcessItem : stockProcessItems) {
            //查询是否还存在于库存表
            Stock stock1 = stockService.getOne(new QueryWrapper<Stock>().eq("id", stockProcessItem.getStockId()));
            //库存表中没有则到零库存中查询
            if (stock1 == null) {
                stock1 = new Stock();
                StockZero stockZero = stockZeroService.getOne(new QueryWrapper<StockZero>().eq("id", stockProcessItem.getStockId()));
                if (stockZero != null) {
                    BeanUtils.copyProperties(stockZero, stock1);
                } else { //库存表与零库存表中都没有则无法进行撤销提交
                    throw new BusinessException("未查询到库存：%s，无法撤销", stockProcessItem.getSn());
                }
            }
            //根据加工明细中的数量进行修改
            stock1.setPackageUnit(stockProcessItem.getPackageUnit())
                    .setPackageQty(1.0)
                    .setSkuUnit(matr.getSkuUnit())
                    .setSkuQty(stockProcessItem.getSkuQty())
                    .setSkuPrice(matr.getSkuPrice())
                    .setAmount(matr.getSkuPrice() * stock.getSkuQty());
            stockService.saveOrUpdate(stock1);
            //删除对应零库存数据
            stockZeroService.remove(new QueryWrapper<StockZero>().eq("id", stockProcessItem.getStockId()));

        }
        //更新被合并的库存明细数量为1
        stockService.update(Wrappers.<Stock>update().in("id", stockProcessItems.stream().map(stockProcessItem -> stockProcessItem.getStockId()).collect(Collectors.toList()))
                .set("package_qty", 1)
                .set("amount", stockProcess.getAmount() / stockProcessItems.size())
                .set("sku_qty", stockProcess.getSkuQty() / stockProcessItems.size()));

        //删除合并的大包装库存
        stockService.removeById(stock.getId());
        stockProcess.setSubmitStatus(false);
        stockLockService.lockBatch(LockBusType.PROCESS, stockProcess.getBusKey(), stockProcess.getWarehouseId(), "加工锁", stockProcessItems.stream().map(StockProcessItem::getSn).collect(Collectors.toList()), stockProcess.getBusKey());
        return super.updateCascadeById(stockProcess);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult submitUp(StockProcess stockProcess) {
        RestResult restResult = RestResult.ok("上架成功");
//        //查询耗材库位
//        LocationLimitMatr locationLimitMatr=locationLimitMatrService.getOne(Wrappers.<LocationLimitMatr>query().eq("matr_id",stockProcess.getMatrId())
//                .eq("warehouse_id",stockProcess.getWarehouseId())
//                . eq("location_type","shelves"));
//        if(locationLimitMatr == null)  throw new BusinessException("【"+stockProcess.getWarehouseName()+"】下面未找到耗材【"+stockProcess.getMatrName()+"】可用的货位");
//        stockProcess.setLocationId(locationLimitMatr.getLocationId()).setLocationName(locationLimitMatr.getLocationName()).setLocationIdcode(locationLimitMatr.getLocationIdcode());
        this.saveOrUpdate(stockProcess);
        this.submit(stockProcess);
        //合并
        if (ProcessTypes.MERGE.getType().equals(stockProcess.getProcessType())) {
            restResult.setMsg(stockService.upShelves(stockProcess.getSn()));
        } else {
            List<StockProcessItem> stockProcessItems = stockProcessItemService.list(new QueryWrapper<StockProcessItem>().eq("process_id", stockProcess.getId()));
            stockProcessItems.forEach(item -> {
                restResult.setMsg(stockService.upShelves(item.getSn()));
            });
        }

        restResult.setData(baseMapper.selectById(stockProcess.getId()));
        return restResult;
    }
}
